//
//  UIButton+YXButton.m
//  YXKit
//
//  Created by ChenJianjun on 15/5/12.
//  Copyright (c) 2015年 yanxiu.com. All rights reserved.
//

#import "UIButton+YXButton.h"
#import "UIImage+YXImage.h"

@implementation UIButton (YXButton)

- (void)yx_exchangeTitleAndImagePosition
{
    if (!self.imageView.image
        || !self.titleLabel.text) {
        return;
    }
    CGSize imageSize = self.imageView.image.size;
    CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font ?:[UIFont systemFontOfSize:14.f]}];
    CGFloat width = CGRectGetWidth(self.bounds);
    if (titleSize.width > width - imageSize.width - 4) {
        titleSize.width = width - 2 * imageSize.width;
    }
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, 0, imageSize.width + 4);
    self.imageEdgeInsets = UIEdgeInsetsMake(0, titleSize.width + 4, 0, -titleSize.width - 4);
}

- (void)yx_setTitleColor:(UIColor *)color image:(UIImage *)image
{
    [self setTitleColor:color forState:UIControlStateNormal];
    UIColor *translucentColor = [color colorWithAlphaComponent:0.5f]; // 半透明色值
    [self setTitleColor:translucentColor forState:UIControlStateHighlighted];
    [self setTitleColor:translucentColor forState:UIControlStateDisabled];
    if (image) {
        [self setImage:image forState:UIControlStateNormal];
        UIImage *translucentImage = [image yx_imageWithColor:translucentColor];
        [self setImage:translucentImage forState:UIControlStateHighlighted];
        [self setImage:translucentImage forState:UIControlStateDisabled];
    }
}

@end
